home *** CD-ROM | disk | FTP | other *** search
- /* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents (ry
- *
- * ***** END LICENSE BLOCK *****
- */
-
- const Cc = Components.classes;
- const Ci = Components.interfaces;
- const Cr = Components.results;
-
- var CacheViewer = {
-
- // ***** Members *****
- _tree: null,
- _bundle: null,
-
- _entries: null,
- _rdf: null,
- _root: null,
- _metaData: "",
- _isOffline: false,
- _visitAll: true,
- _isLoading: false,
-
- get _cacheService() {
- if (!this.__cacheService) {
- this.__cacheService = Cc["@mozilla.org/network/cache-service;1"]
- .getService(Ci.nsICacheService);
- }
- return this.__cacheService;
- /*
- return Cc["@mozilla.org/network/cache-service;1"]
- .getService(Ci.nsICacheService);
- */
- },
- __cacheService: null,
-
- get _dateService() {
- if (!this.__dateService) {
- this.__dateService = Cc["@mozilla.org/intl/scriptabledateformat;1"]
- .getService(Ci.nsIScriptableDateFormat);
- }
- return this.__dateService;
- },
- __dateService: null,
-
- // ***** CacheViewer *****
- init: function CV_init() {
- var ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
- this._isOffline = ioService.offline;
-
- this._tree = document.getElementById("cacheTree");
- this._bundle = document.getElementById("strings");
-
- this._entries = new Array();
- this._rdf = new RDF();
- this._root = this._rdf.makeSeqContainer(this._rdf.RDF_ITEM_ROOT);
-
- this._tree.database.AddDataSource(this._rdf.datasource);
- this._tree.setAttribute("ref", this._rdf.RDF_ITEM_ROOT);
-
- this._visitAll = true;
- this._cacheService.visitEntries(this);
-
- var it = Iterator(this._entries);
-
- var timer = Components.classes["@mozilla.org/timer;1"]
- .createInstance(Components.interfaces.nsITimer);
-
- var self = this;
-
- function timerCallback() {}
- timerCallback.prototype = {
- observe: function(aTimer, aTopic, aData) {
- try { var [index, value] = it.next(); }
- catch(e) { self._toggleButton(self._isLoading = false); return; }
-
- if (!self._rdf) return;
-
- //self._rdf.datasource.beginUpdateBatch();
- var resource = self._rdf.appendResource(index, self._root);
- self._rdf.setLiteralProperty(resource, self._rdf.NS_CACHEVIEWER+"key", value[0]);
- self._rdf.setIntProperty(resource, self._rdf.NS_CACHEVIEWER+"size", value[1]);
- self._rdf.setLiteralProperty(resource, self._rdf.NS_CACHEVIEWER+"dev", value[2]);
- self._rdf.setLiteralProperty(resource, self._rdf.NS_CACHEVIEWER+"clnt", value[3]);
- self._rdf.setLiteralProperty(resource, self._rdf.NS_CACHEVIEWER+"strm", value[4]);
- self._rdf.setDateProperty(resource, self._rdf.NS_CACHEVIEWER+"mod", value[5]*1000000);
- self._rdf.setDateProperty(resource, self._rdf.NS_CACHEVIEWER+"fet", value[6]*1000000);
- self._rdf.setDateProperty(resource, self._rdf.NS_CACHEVIEWER+"exp", value[7]*1000000);
- self._rdf.setIntProperty(resource, self._rdf.NS_CACHEVIEWER+"cnt", value[8]);
- self._rdf.setLiteralProperty(resource, self._rdf.NS_CACHEVIEWER+"type", self._getMimeType(value[0], value[3], value[4]));
- //self._getMimeType(resource, value[0], value[3], value[4]);
- //self._rdf.datasource.endUpdateBatch();
- timer.init(new timerCallback(), 0, timer.TYPE_ONE_SHOT);
- }
- };
-
- this._toggleButton(this._isLoading = true);
- timer.init(new timerCallback(), 0, timer.TYPE_ONE_SHOT);
- },
-
- finish: function CV_finish() {
- var ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
- ioService.offline = this._isOffline;
-
- this._root = null;
- this._rdf = null;
- this._entries = null;
- this._bundle = null;
- this._tree = null;
- },
-
- openCache: function CV_openCache() {
- var resource = this._getResourceAtCurrentIndex();
- if (!resource) return;
-
- var key = this._rdf.getLiteralProperty(resource.Value, this._rdf.NS_CACHEVIEWER+"key");
- var client = this._rdf.getLiteralProperty(resource.Value, this._rdf.NS_CACHEVIEWER+"clnt");
- var stream = this._rdf.getLiteralProperty(resource.Value, this._rdf.NS_CACHEVIEWER+"strm") == "true" ? "1" :"0";
-
- this._getBrowser().selectedTab = this._getBrowser().addTab(key);
- },
-
- deleteCache: function CV_deleteCache() {
- var resource = this._getResourceAtCurrentIndex();
- if (!resource) return;
-
- var key = this._rdf.getLiteralProperty(resource.Value, this._rdf.NS_CACHEVIEWER+"key");
- var client = this._rdf.getLiteralProperty(resource.Value, this._rdf.NS_CACHEVIEWER+"clnt");
- var stream = this._rdf.getLiteralProperty(resource.Value, this._rdf.NS_CACHEVIEWER+"strm") == "true" ? true : false;
- var entry = this._openCacheEntry(key, client, stream);
- if (!entry) return;
-
- entry.doom();
- entry.close();
-
- this._updateUI();
- },
-
- reloadCache: function CV_reloadCache() {
- if (this._isLoading) return;
-
- var image = document.getElementById("previewImage");
- image.src = "";
- document.getElementById("cacheInfo").value = "";
-
- this._tree.database.RemoveDataSource(this._rdf.datasource);
- this._tree.builder.rebuild();
-
- this._rdf = null;
- this.__cacheService = null;
-
- this.init();
- },
-
- saveCache: function CV_saveCache() {
- var selection = [];
- var rangeCount = this._tree.view.selection.getRangeCount();
- for (var i=0; i<rangeCount; ++i) {
- var rangeMin = {};
- var rangeMax = {};
- this._tree.view.selection.getRangeAt(i, rangeMin, rangeMax);
- for (var j=rangeMin.value; j<=rangeMax.value; ++j) {
- selection.push(this._tree.view.getResourceAtIndex(j));
- }
- }
-
- if (selection.length == 1) {
- var key = this._rdf.getLiteralProperty(selection[0], this._rdf.NS_CACHEVIEWER+"key");
- saveURL(key, null, null, false);
- return;
- }
-
- var pref = Cc["@mozilla.org/preferences-service;1"]
- .getService(Ci.nsIPrefService)
- .getBranch("extensions.cacheviewer.");
- var lastFolderPath = pref.getComplexValue("folder", Ci.nsISupportsString).data;
- var lastFolder = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile)
- if (lastFolderPath)
- lastFolder.initWithPath(lastFolderPath);
-
- var fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
- fp.init(window, null, Ci.nsIFilePicker.modeGetFolder);
- fp.displayDirectory = lastFolder;
- var res = fp.show();
- if (res != Ci.nsIFilePicker.returnOK)
- return;
-
- var str = Cc["@mozilla.org/supports-string;1"].createInstance(Ci.nsISupportsString);
- str.data = fp.file.path;
- pref.setComplexValue("folder", Ci.nsISupportsString, str);
-
- var folder = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
- folder.initWithPath(fp.file.path);
-
- var URIFix = Cc["@mozilla.org/docshell/urifixup;1"].getService(Ci.nsIURIFixup);
-
- for (i=0; i<selection.length; i++) {
- var key = this._rdf.getLiteralProperty(selection[i], this._rdf.NS_CACHEVIEWER+"key");
- var client = this._rdf.getLiteralProperty(selection[i], this._rdf.NS_CACHEVIEWER+"clnt");
- var stream = this._rdf.getLiteralProperty(selection[i], this._rdf.NS_CACHEVIEWER+"strm") == "true" ? true : false;
- var device = this._rdf.getLiteralProperty(selection[i], this._rdf.NS_CACHEVIEWER+"dev");
-
- var descriptor = this._openCacheEntry(key, client, stream);
- if (!descriptor) {
- continue;
- }
-
- var URI = URIFix.createFixupURI(key, 0);
- var fileInfo = new FileInfo();
- initFileInfo(fileInfo, URI.spec, null, null, null, null);
- var file = folder.clone();
- file.append(fileInfo.fileBaseName+"."+fileInfo.fileExt);
- file.createUnique(Ci.nsILocalFile.NORMAL_FILE_TYPE, 0666);
-
- // If memory cache, use "internalSave".
- // (See chrome://chrome://global/content/contentAreaUtils.js)
- if (device == "memory") {
- var auto = new AutoChosen(file, makeURI(key));
- internalSave(key, null, null, null,
- null, false, null,
- auto, null, true);
- continue;
- }
-
- // Check the encoding.
- var metaData = "";
- var encode = "";
- var visitor = {
- visitMetaDataElement: function(aKey, aValue) {
- metaData += aKey + ": " + aValue + "\n";
- return true;
- }
- };
- descriptor.visitMetaData(visitor);
- if (metaData.match(/Content-Encoding: (.+)$/m)) {
- encode = RegExp.$1;
- }
-
- try {
- var inputStream = descriptor.openInputStream(0);
-
- if (encode) {
- var converterService = Cc["@mozilla.org/streamConverters;1"]
- .getService(Ci.nsIStreamConverterService);
- var converter = converterService.asyncConvertData(encode, "uncompressed", new StreamListener(file), null);
- converter.onStartRequest(null, null);
- converter.onDataAvailable(null, null, inputStream, 0, inputStream.available());
- converter.onStopRequest(null, null, null);
- continue;
- }
-
- var fileOutputStream = Cc["@mozilla.org/network/file-output-stream;1"]
- .createInstance(Ci.nsIFileOutputStream);
- var binaryInputStream = Cc["@mozilla.org/binaryinputstream;1"]
- .createInstance(Ci.nsIBinaryInputStream);
- binaryInputStream.setInputStream(inputStream);
- var content = binaryInputStream.readBytes(binaryInputStream.available());
- fileOutputStream.init(file, -1, 0666, 0);
- fileOutputStream.write(content, content.length);
- fileOutputStream.flush();
- } catch(e) {
- dump(e+"\n");
- file.remove(false);
- }
- binaryInputStream.close();
- fileOutputStream.close();
- }
- },
-
- search: function CV_search(aSearchString) {
- aSearchString = aSearchString.replace(/^ +/, "");
- if (aSearchString) {
- this._rdf.search(aSearchString);
- this._tree.ref = this._rdf.RDF_ITEM_SEARCH;
- } else {
- this._tree.ref = this._rdf.RDF_ITEM_ROOT;
- }
- document.getElementById("showall").disabled = !aSearchString;
- },
-
- showAll: function CV_showAll() {
- var textbox = document.getElementById("search");
- textbox.value = "";
- textbox.focus();
- this.search("");
- },
-
- onSelect: function CV_onSelect() {
- if (this._tree.view.selection.count == 1) {
- var timer = Components.classes["@mozilla.org/timer;1"]
- .createInstance(Components.interfaces.nsITimer);
- var self = this;
- function timerCallback() {}
- timerCallback.prototype = {
- observe: function(aTimer, aTopic, aData) {
- self._makePreview(self._tree.view.selection.currentIndex);
- }
- }
- timer.init(new timerCallback(), 0, timer.TYPE_ONE_SHOT);
- }
- },
-
- onPopupShowing: function CV_onPopupShowing() {
- var resource = this._getResourceAtCurrentIndex();
- if (!resource) return;
-
- var dev = this._rdf.getLiteralProperty(resource.Value, this._rdf.NS_CACHEVIEWER+"dev");
- var menu = document.getElementById("deleteCache");
- if (dev != "disk")
- menu.setAttribute("disabled", "true");
- else
- if (menu.hasAttribute("disabled"))
- menu.removeAttribute("disabled");
- },
-
- resize: function CV_resize() {
- var image = document.getElementById("previewImage");
- if (image.hasAttribute("style")) {
- image.removeAttribute("style");
- return;
- }
-
- var width = parseInt(window.getComputedStyle(image, "").width.replace("px", ""));
- var height = parseInt(window.getComputedStyle(image, "").height.replace("px", ""));
-
- var containerWidth = parseInt(window.getComputedStyle(image.parentNode.parentNode, "").width.replace("px", ""));
- var containerHeight = parseInt(window.getComputedStyle(image.parentNode.parentNode, "").height.replace("px", ""));
-
- if (width > containerWidth) {
- var zoomX = containerWidth / width;
- width = containerWidth - 2;
- height = height * zoomX - 2;
- }
- if (height > containerHeight) {
- var zoomY = containerHeight / height;
- height = containerHeight - 2;
- width = width * zoomY - 2;
- }
- image.setAttribute("style", "width:"+width+"px;"+"height:"+height+"px;");
- },
-
- // ***** nsICacheVisitor *****
- visitDevice: function CV_visitDevice(aDeviceID, aDeviceInfo) {
- if (aDeviceID == "offline") return true;
-
- document.getElementById(aDeviceID).setAttribute("value", Math.round(aDeviceInfo.totalSize/1024000*100)/100+"/"+Math.round(aDeviceInfo.maximumSize/1024000*100)/100);
- document.getElementById(aDeviceID + "Meter").setAttribute("value", Math.round(aDeviceInfo.totalSize/aDeviceInfo.maximumSize*100));
- document.getElementById(aDeviceID + "Entries").setAttribute("value", aDeviceInfo.entryCount +" "+ this._bundle.getString("entries"));
- return true;
- },
-
- visitEntry: function CV_visitEntry(aDeviceID, aEntryInfo) {
- if (!this._visitAll)
- return false;
-
- if (aEntryInfo.dataSize == 0)
- return true;
-
- if (aEntryInfo.key.indexOf("http") == 0) {
- var temp = [aEntryInfo.key,
- aEntryInfo.dataSize,
- aEntryInfo.deviceID,
- aEntryInfo.clientID,
- aEntryInfo.isStreamBased(),
- aEntryInfo.lastFetched,
- aEntryInfo.lastModified,
- aEntryInfo.expirationTime,
- aEntryInfo.fetchCount];
- this._entries.push(temp);
- }
- return true;
- },
-
- // ***** nsICacheMetaDataVisitor *****
- visitMetaDataElement: function CV_visitMetaDataElement(aKey, aValue) {
- this._metaData += aKey + ": " + aValue + "\n";
- return true;
- },
-
- // ***** Helper funcitons *****
- _makePreview: function CV__makePreview(aRow) {
- var resource = this._tree.view.getResourceAtIndex(aRow);
-
- var key = this._rdf.getLiteralProperty(resource.Value, this._rdf.NS_CACHEVIEWER+"key");
- var device = this._rdf.getLiteralProperty(resource.Value, this._rdf.NS_CACHEVIEWER+"dev");
- var type = this._rdf.getLiteralProperty(resource.Value, this._rdf.NS_CACHEVIEWER+"type");
- var client = this._rdf.getLiteralProperty(resource.Value, this._rdf.NS_CACHEVIEWER+"clnt");
- var stream = this._rdf.getLiteralProperty(resource.Value, this._rdf.NS_CACHEVIEWER+"strm") == "true" ? true : false;
-
- var descriptor = this._openCacheEntry(key, client, stream);
- if (!descriptor) return;
-
- var value = this._bundle.getString("key") + " " + descriptor.key + "\n" +
- this._bundle.getString("size") + " " + descriptor.dataSize + " bytes\n" +
- this._bundle.getString("count") + " " + descriptor.fetchCount + "\n" +
- this._bundle.getString("modified") + " " + this._formatDate(descriptor.lastModified*1000000) + "\n" +
- this._bundle.getString("fetched") + " " + this._formatDate(descriptor.lastFetched*1000000) + "\n" +
- this._bundle.getString("expiration") + " ";
-
- if (parseInt(0xFFFFFFFF) <= descriptor.expirationTime)
- value += this._bundle.getString("noexpiration") + "\n";
- else
- value += this._formatDate(this._rdf.getDateProperty(resource.Value, this._rdf.NS_CACHEVIEWER+"exp")) + "\n";
-
- value += this._bundle.getString("fileondisk") + " ";
-
- var cacheFile;
- try { cacheFile = descriptor.file; } catch(e) { cacheFile = null; }
- if (cacheFile)
- value += cacheFile.path + "\n\n";
- else
- value += this._bundle.getString("nofile") + "\n\n";
-
- this._metaData = "";
- descriptor.visitMetaData(this);
- value += this._metaData;
- descriptor.close();
-
- document.getElementById("cacheInfo").value = value;
-
- // Load only from cache.
- var ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
- ioService.offline = true;
-
- var url = "chrome://cacheviewer/content/not_image.png";
- if ((type.indexOf("image") == 0) ||
- (key.match(/.*(\.png|\.gif|\.jpg|\.ico|\.bmp)$/i))) {
- url = key;
- }
-
- var image = document.getElementById("previewImage");
- image.src = url;
- if (image.hasAttribute("style"))
- image.removeAttribute("style");
-
- var self = this;
- image.onload = function() {
- self.resize();
- }
- ioService.offline = this._isOffline;
- },
-
- _getResourceAtCurrentIndex: function CV__getResourceAtCurrentIndex() {
- if (!this._tree.view.selection || this._tree.view.selection.count != 1)
- return null;
-
- return this._tree.view.getResourceAtIndex(this._tree.view.selection.currentIndex);
- },
-
- _getBrowser: function CV__getBrowser() {
- return this._getTopWin().document.getElementById("content");
- },
-
- _getTopWin: function CV__getTopWin() {
- var windowManager = Cc["@mozilla.org/appshell/window-mediator;1"].getService();
- var windowManagerInterface = windowManager.QueryInterface(Ci.nsIWindowMediator);
- return windowManagerInterface.getMostRecentWindow("navigator:browser");
- },
-
- _updateUI: function CV_updateUI() {
- var currentIndex = this._tree.view.selection.currentIndex;
-
- this._rdf.removeResource(this._getResourceAtCurrentIndex(), this._rdf.getContainer(this._rdf.RDF_ITEM_ROOT));
- if (this._tree.ref == this._rdf.RDF_ITEM_SEARCH)
- this._rdf.removeResource(this._getResourceAtCurrentIndex(), this._rdf.getContainer(this._rdf.RDF_ITEM_SEARCH));
- var rowCount = this._tree.view.rowCount;
-
- if (currentIndex == rowCount)
- currentIndex--;
- if (rowCount > 0)
- this._tree.view.selection.select(currentIndex);
- else
- document.getElementById("cacheInfo").value = "";
-
- var cacheService = Cc["@mozilla.org/network/cache-service;1"]
- .getService(Ci.nsICacheService);
- this._visitAll = false;
- cacheService.visitEntries(this);
- },
-
- _toggleButton: function CV__toggleButton(aIsLoading) {
- var reload = document.getElementById("reload");
- if (aIsLoading) {
- if (reload.hasAttribute("enable"))
- reload.removeAttribute("enable");
- } else {
- reload.setAttribute("enable", "true");
- }
- },
-
- _formatDate: function CV__formatDate(aTime) {
- var date = new Date(aTime/1000);
- return this._dateService.FormatDateTime("",
- this._dateService.dateFormatLong,
- this._dateService.timeFormatSeconds,
- date.getFullYear(),
- date.getMonth()+1,
- date.getDate(),
- date.getHours(),
- date.getMinutes(),
- date.getSeconds());
- },
- /*
- _getMimeType: function CV__getMimeType(aResource, aKey, aClientID, aStreamBased) {
- var self = this;
- function CacheListener(resource) {
- this._resource = resource;
- }
- CacheListener.prototype = {
- onCacheEntryAvailable: function(aDescriptor, aAccessGranted, aStatus) {
- var type = "-";
- if (aDescriptor && aStatus == Cr.NS_OK) {
- try {
- var header = aDescriptor.getMetaDataElement("response-head")
- .match(/^Content-Type:\s*(.*?)\s*(?:\;|$)/mi);
- } catch(e) {
- } finally {
- aDescriptor.close();
- }
- if (header)
- type = header[1];
- }
- self._rdf.setLiteralProperty(this._resource, self._rdf.NS_CACHEVIEWER+"type", type);
- }
- };
- try {
- var session = this._cacheService.createSession(aClientID, Ci.nsICache.STORE_ANYWHERE, aStreamBased);
- session.doomEntriesIfExpired = false;
- session.asyncOpenCacheEntry(aKey, Ci.nsICache.ACCESS_READ, new CacheListener(aResource));
- } catch(e) {
- dump(e+"\n");
- this._rdf.setLiteralProperty(aResource, this._rdf.NS_CACHEVIEWER+"type", "-");
- }
- },
- */
- _getMimeType: function CV__getMimeType(aKey, aClientID, aStreamBased) {
- var descriptor = this._openCacheEntry(aKey, aClientID, aStreamBased);
- if (!descriptor)
- return "-";
-
- var retval = "-";
- try {
- var header = descriptor.getMetaDataElement("response-head")
- .match(/^Content-Type:\s*(.*?)\s*(?:\;|$)/mi);
- } catch(e) {
- descriptor.close();
- return retval;
- }
- descriptor.close();
- if (header)
- retval = header[1];
- return retval;
- },
-
- _openCacheEntry: function CV__openCacheEntry(aKey, aClientID, aStreamBased) {
- try {
- var session = this._cacheService.createSession(aClientID, Ci.nsICache.STORE_ANYWHERE, aStreamBased);
- session.doomEntriesIfExpired = false;
- return session.openCacheEntry(aKey, Ci.nsICache.ACCESS_READ, false);
- } catch(e) {
- //dump(e+"\n");
- // 0x804b003d NS_ERROR_CACHE_KEY_NOT_FOUND
- // 0x804b0040 NS_ERROR_CACHE_WAIT_FOR_VALIDATION
- // 0x804b0044 NS_ERROR_CACHE_IN_USE
- return null;
- }
- }
- };
-
- // ***** StreamListener for Asynchronous Converter *****
- function StreamListener(aFile) {
- this._file = aFile;
- this._data = null;
- }
-
- StreamListener.prototype = {
-
- onStartRequest: function(aRequest, aContext) {},
-
- onStopRequest: function(aRequest, aContext, aStatusCode) {
- var fileOutputStream = Cc["@mozilla.org/network/file-output-stream;1"]
- .createInstance(Ci.nsIFileOutputStream);
- try {
- fileOutputStream.init(this._file, -1, 0666, 0);
- fileOutputStream.write(this._data, this._data.length);
- fileOutputStream.flush();
- } catch(e) {
- dump(e+"\n");
- this._file.remove(false);
- } finally {
- fileOutputStream.close();
- }
- },
-
- onDataAvailable: function(aRequest, aContext, aInputStream, aOffset, aCount) {
- var binaryInputStream = Cc["@mozilla.org/binaryinputstream;1"]
- .createInstance(Ci.nsIBinaryInputStream);
- binaryInputStream.setInputStream(aInputStream);
- this._data += binaryInputStream.readBytes(binaryInputStream.available());
- binaryInputStream.close();
- }
- };
-